#include "temp.h"
#include "work.h"
#include "peripheral.h"
#include "adc.h"

extern uint8_t Work_Mode,Error_State,Trigger_State;
extern boolean_t Trigger_Continuous;
uint8_t temp_cnt,FAN_Temp=25,CAP_Temp=25,over_cnt;

//25~90
const uint16_t Temp_AD[]=
{
//10K3950
2048,
2003,
1959,
1914,
1870,
1827,
1784,
1741,
1699,
1658,
1617,
1577,
1537,
1498,
1459,
1421,
1384,
1348,
1312,
1277,
1243,
1209,
1176,
1144,
1112,
1082,
1052,
1022,
994,
966,
938,
912,
886,
861,
836,
812,
789,
766,
744,
723,
702,
682,
662,
643,
624,
606,
589,
572,
555,
539,
524,
509,
494,
480,
466,
453,
440,
427,
415,
403,
392,
381,
370,
360,
349,
340,

};

uint16_t filter(uint8_t value)
{
		static uint8_t filter_data[10]={25,25,25,25,25,25,25,25,25,25};
		uint8_t i;
		uint16_t result=0;
		for(i=0;i<9;i++)
		{
				filter_data[i]=filter_data[i+1];
				result+=filter_data[i];
		}
		filter_data[9]=value;
		result+=filter_data[9];
		result/=10;
		return result;
}

void Temp_Protect()		//�¶ȱ���
{
		uint32_t AD_Result1,AD_Result2;
		uint8_t i;
		temp_cnt++;
		if(temp_cnt>30)
		{
				temp_cnt=0;
				ADC_Ref(AdcMskRefVolSelAVDD);
				AD_Result1 = ADC_Convert(NTC_FAN_Channel);
				AD_Result2 = ADC_Convert(NTC_CAP_Channel);
				ADC_Ref(AdcMskRefVolSelInBgr2p5);
				for(i=0;i<=(91-25);i++)
				{
						if(AD_Result1>Temp_AD[i])
						break;
				}
				FAN_Temp = (i+25+FAN_Temp)/2;
				// 2025/04/23谭剑说风扇 的ntc暂时不贴了，因为有漏电的情况，暂时还没找到原因
				FAN_Temp = 25;
				AD_Result1 = 1024;

				for(i=0;i<=(91-25);i++)
				{
						if(AD_Result2>Temp_AD[i])
						break;
				}
				CAP_Temp = (i+25+CAP_Temp)/2;
				if(AD_Result1>4050||AD_Result1<30||AD_Result2>4050||AD_Result2<30)
				{
						Error_State|=NTC_ERROR;
				}
				else
				{
						Error_State&=~NTC_ERROR;
						if(Work_Mode)
						{
								if(FAN_Temp>70||CAP_Temp>70)
								{
										over_cnt++;
										if(over_cnt>9)
										{
												over_cnt=0;
												Error_State|=TEMP_OVER;
												Trigger_Continuous=0;
												Trigger_State=Trigger_End;
										}
								}
						}
						if(FAN_Temp<65&&CAP_Temp<65)
						{
								over_cnt=0;
						}
						if(FAN_Temp<60&&CAP_Temp<60)
						{
								Error_State&=~TEMP_OVER;	
						}
				}
				if(Error_State&NTC_ERROR)	//�¶��쳣�ػ�
				{
						if(Work_Mode)
						Work_Mode=0;
				}
		}
}
